<template>
  <div ref="chart" class="c">

  </div>
 
</template>

<script lang="ts" setup>
import {ref, onMounted, watch} from 'vue'
import * as echarts from 'echarts'
import {useCsvStore} from '../../stores/csvStore'

const csvStore = useCsvStore()
const chart = ref<HTMLElement | null>(null)
let myChart: echarts.ECharts | null = null

onMounted(() => {
  if(chart.value){
    myChart = echarts.init(chart.value, 'dark')
    renderChart()
  }
})

watch(()=>csvStore.csvData, () => {
  renderChart()
})

const  getHighlightPoints = (data: any[], count: number) => {
  if(data.length <= count) return data
  const shuffled = data.slice().sort(() => 0.5 - Math.random());
  return shuffled.slice(0, count);
}

const renderChart = () => {
  if(!myChart || csvStore.csvData.length === 0) return

  const xAxisData = csvStore.csvData.map((row: any) => row[Object.keys(row)[0]])
  const yAxisData = csvStore.csvData.map((row: any) => parseFloat(row[Object.keys(row)[1]]))

  const highlightPoints = getHighlightPoints(csvStore.csvData, 3)
  const highlightData = highlightPoints.map((row: any) => ({
    name: row[Object.keys(row)[0]],
    value: [row[Object.keys(row)[0]], parseFloat(row[Object.keys(row)[1]])],
    symbol: 'circle',
    symbolSize: 10,
    itemStyle:{
      color: '#FF0000',
    }
  }))

  const option: echarts.EchartOption = {
    title: {
      text: 'CSV 数据折线图',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      name: Object.keys(csvStore.csvData[0])[0],
    },
    yAxis: {
      type: 'value',
      name: Object.keys(csvStore.csvData[0])[1] ,
    },
    series: [
      {
        name: '数据',
        type: 'line',
        data: yAxisData,
        symbol: 'none',
        lineStyle: {
          color: '#5470C6',
          width: 2,
        }
      },

      {
        name: '突出显示点',
        type: 'scatter',
        data: highlightData,
        symbol: 'circle',
        symbolSize: 10,
        itemStyle:{
          color: '#FF0000',
        }
      },
    ]
  }

  myChart.setOption(option)
}
</script>

<style scoped>
 .c {
    width: 870px;
    height: 650px;
    background-color: aliceblue;
  }
</style>
